
package com.ibpd.henuocms.common;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
 
/**
 * txt文件读写工具类
 * @author MG
 */
public class TxtUtil {
	public static String readTxtFile(String filePath){
		return readTxtFile(filePath,"UTF-8");
	}
	public static String readTxtFile(String filePath,String characterSet){
		StringBuffer sb=new StringBuffer();
		  try {
              String encoding=characterSet;
              File file=new File(filePath);
              if(file.isFile() && file.exists()){ //判断文件是否存在
                  InputStreamReader read = new InputStreamReader(
                  new FileInputStream(file),encoding);//考虑到编码格�?
                  BufferedReader bufferedReader = new BufferedReader(read);
                  String lineTxt = null;
                  while((lineTxt = bufferedReader.readLine()) != null){
                      sb.append(lineTxt+"\n");
                  }
                  read.close();
      }else{
    	  IbpdLogger.getLogger(TxtUtil.class).info("找不到指定的文件");
      }
      } catch (Exception e) {
    	  IbpdLogger.getLogger(TxtUtil.class).info("读取文件内容出错");
          e.printStackTrace();
      }
      return sb.toString();
	}
   
     
    public static void main(String argv[]){
        String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt";
//      "res/";
        readTxtFile(filePath);
    }
    public static boolean writeTxtFile(String content,File  fileName)throws Exception{  
    	return writeTxtFile(content,fileName,"UTF-8");
    }
    public static boolean writeTxtFile(String content,File  fileName,String characterSet)throws Exception{  
    	  RandomAccessFile mm=null;  
    	  boolean flag=false;  
    	  FileOutputStream o=null;  
    	  try {  
    	   o = new FileOutputStream(fileName);  
    	      o.write(content.getBytes(characterSet));  
    	      o.close();  
    	//   mm=new RandomAccessFile(fileName,"rw");  
    	//   mm.writeBytes(content);   
    	   flag=true;  
    	  } catch (Exception e) {  
    	   // TODO: handle exception  
    	   e.printStackTrace();  
    	  }finally{  
    	   if(mm!=null){  
    	    mm.close();  
    	   }  
    	  }  
    	  return flag;  
    	 }  
 
}